﻿using System;
using System.ServiceModel.Channels;
using System.Xml.Linq;
using Core.Ndatax.Domain.Dto;
using Core.Ndatax.Infrastructure.Entitys;
using Xman.Extensions.Core;

namespace Core.Ndatax.Infrastructure.Common
{
    public class HL7Helper
    {
        public const string AddRequest = "JH0201";
        public const string DelRequest = "JH0204";
        public const string UpdateExamState = "JH0405";
        public const string AddRes = "JH0504";
        public const string UpdateRes = "JH0505";

        public static string CreateReturnXml(string eventValue, string message)
        {
            var result = message.IsNullOrEmpty() ? "AA" : "AE";
            var xml = $@"<MCCI_IN000002UV01 xmlns='urn:hl7-org:v3' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' ITSVersion='XML_1.0' xsi:schemaLocation='urn:hl7-org:v3 ../multicacheschemas/MCCI_IN000002UV01.xsd'>
	<!-- 消息ID extension请使用GUID生成-->
	<id root='2.16.156.10011.0' extension='{Guid.NewGuid()}'/>
	<!-- 消息创建时间 -->
	<creationTime value='{DateTime.Now:yyyyMMddHHmmss}'/>
	<!-- 服务标识,extension为唯一事件编码，区分响应的服务事件 -->
	<interactionId root='2.16.840.1.113883.1.6' extension='{eventValue}'/>
	<!-- 消息用途: P(Production); D(Debugging); T(Training) -->
	<processingCode code='P'/>
	<!-- 消息处理模式: '取值可以为以下列出值中任意一个，正式使用时设置为''T''A(Archive);I(Initial load); R(Restore from archive); T(Current processing)' -->
	<processingModeCode code='R'/>
	<!-- 消息应答: '取值可以为以下列出值中任意一个，正式使用时设置为''NE''AL(Always); ER(Error/reject only); NE(Never)'-->
	<acceptAckCode code='NE'/>
	<!--接收方信息-->
	<receiver typeCode='RCV'>
		<device classCode='DEV' determinerCode='INSTANCE'>
			<!-- 接受者ID root为OID -->
			<id root='2.16.156.10011.0.1.1' extension=''/>
		</device>
	</receiver>
	<!--发送方信息-->
	<sender typeCode='SND'>
		<device classCode='DEV' determinerCode='INSTANCE'>
			<!-- 发送者ID root为OID -->
			<id root='2.16.156.10011.0.1.2' extension=''/>
		</device>
	</sender>
	<!--typeCode 为处理结果，AA表示成功 AE 表示失败-->
	<acknowledgement typeCode='{result}'>
		<targetMessage>
			<!-- 请求的消息ID-->
			<id root='2.16.156.10011.0' extension='请求的消息ID'/>
		</targetMessage>
		<acknowledgementDetail>
			<!-- 处理结果说明-->
			<text>{message}</text>
		</acknowledgementDetail>
	</acknowledgement>
</MCCI_IN000002UV01>";
            xml = xml.Replace("\'", "\"");
            return xml;
        }

        public static AddRequestDto CreateAddRequestDto(XElement element)
        {
            var dto = new AddRequestDto();
            var el_request = element.Element("controlActProcess").Element("subject").Element("observationRequest");
            var el_examinfos = el_request?.Elements("component2").ToXList();

            var el_encounter = el_request.Element("componentOf1").Element("encounter");//就诊信息
            var el_paientinfo = el_encounter.Element("subject").Element("patient");
            #region requestInfo

            dto.TvpRequest.SheetID = el_request.ElementPath("id/item").GetAttributeValue("extension");
            dto.TvpRequest.ClinicalDiagnosis = el_encounter.ElementPath("pertinentInformation1/observationDx/value/displayName").GetAttributeValue();
            dto.TvpRequest.ExamPurpose = el_request.Element("text").GetAttributeValue();
            dto.TvpRequest.BillingDeptCode = el_request.ElementPath("author/assignedEntity/representedOrganization/id/item").GetAttributeValue("extension");
            dto.TvpRequest.BillingDeptName = el_request.ElementPath("author/assignedEntity/representedOrganization/name/item/part").GetAttributeValue();
            dto.TvpRequest.ExamDeptCode = el_examinfos?[0].ElementPath("observationRequest/location/serviceDeliveryLocation/serviceProviderOrganization/id/item").GetAttributeValue("extension");
            dto.TvpRequest.IsEmergent = el_request.ElementPath("priorityCode/displayName").GetAttributeValue() == "常规" ? "0" : "1";
            dto.TvpRequest.ReqSheetDoctorID = el_request.ElementPath("author/assignedEntity/id/item").GetAttributeValue("extension");
            dto.TvpRequest.ReqSheetDoctor = el_request.ElementPath("author/assignedEntity/assignedPerson/name/item/part").GetAttributeValue();
            var time = el_request.ElementPath("author/time").GetAttributeValue();
            dto.TvpRequest.ReqSheetDate = time?.Substring(0, 8);
            dto.TvpRequest.ReqSheetTime = time?[8..].PadRight(6, '0');
            dto.TvpRequest.PatientAdmitDate = dto.TvpRequest.ReqSheetDate;
            var patientstyle = el_encounter.Element("code").GetAttributeValue("code");
            dto.TvpRequest.PatientStyle = patientstyle == "1" ? "0" : patientstyle == "2" ? "1" : patientstyle == "3" ? "2" : patientstyle;
            var items = el_encounter.Element("id")?.Elements("item").ToXList();
            dto.TvpRequest.OutPatientID = items?[0].GetAttributeValue("extension");
            dto.TvpRequest.InPatientID = items?[1].GetAttributeValue("extension");
			dto.TvpRequest.PatientAdmitTimes = "";
            dto.TvpRequest.PatientJZLSH = items?[3].GetAttributeValue("extension");
            dto.TvpRequest.PatientName = el_paientinfo.ElementPath("patientPerson/name/item/part").GetAttributeValue();
            dto.TvpRequest.PatientSex = el_paientinfo.ElementPath("patientPerson/administrativeGenderCode").GetAttributeValue("code");
            dto.TvpRequest.PatientBirth = el_paientinfo.ElementPath("patientPerson/birthTime").GetAttributeValue();
            dto.TvpRequest.PatientAge = el_paientinfo.ElementPath("patientPerson/birthTime/originalText").GetAttributeValue();

            var patientitems = el_paientinfo.Element("id")?.Elements("item")?.ToXList();
            dto.TvpRequest.PatientID = patientitems?[0].GetAttributeValue("extension");
            dto.TvpRequest.PatientCardID = patientitems?[2].GetAttributeValue("extension");

            dto.TvpRequest.PatientWardNo = el_encounter.ElementPath("location/serviceDeliveryLocation/serviceProviderOrganization/asOrganizationPartOf/wholeOrganization/id/item").GetAttributeValue("extension");
			dto.TvpRequest.PatientBedNo = el_encounter.ElementPath("location/serviceDeliveryLocation/location/id/item").GetAttributeValue("extension");
            dto.TvpRequest.PatientHomeTel = el_paientinfo.ElementPath("patientPerson/telecom/item").GetAttributeValue();
            dto.TvpRequest.PatientHomeAddress = el_paientinfo.ElementPath("patientPerson/addr/item/part").GetAttributeValue();
            dto.TvpRequest.PatientRegAddress = dto.TvpRequest.PatientHomeAddress;
            var patientcarditems = el_paientinfo.ElementPath("patientPerson/id")?.Elements("item").ToXList();
            dto.TvpRequest.MedicalCardNum = patientcarditems?[1].GetAttributeValue("extension");
            dto.TvpRequest.PatientIdentityNo = patientcarditems?[0].GetAttributeValue("extension");
            dto.TvpRequest.MedicalHistory = el_request.ElementPath("pertinentInformation/observation/value").GetAttributeValue();
            dto.TvpRequest.ThirdSheetId = dto.TvpRequest.SheetID;
            dto.TvpRequest.ThirdPatientHomeTel = dto.TvpRequest.PatientHomeTel;
            dto.TvpRequest.RequestState = "0";

            #endregion

            #region RequestExam,RequestFee

            foreach (var el_examinfo in el_examinfos)
            {
                TvpRequestExam requestExam = new();
                requestExam.SheetID = dto.TvpRequest.SheetID;
                requestExam.ExamID = el_examinfo.ElementPath("observationRequest/code").GetAttributeValue("code");
                requestExam.OrderID = el_examinfo.ElementPath("observationRequest/id/item").GetAttributeValue("extension");
				var bodyCode= el_examinfo.ElementPath("observationRequest/targetSiteCode/item").GetAttributeValue("code");
                requestExam.ItemCode = requestExam.ExamID+ bodyCode;
                requestExam.ExamProject = el_examinfo.ElementPath("observationRequest/code/displayName").GetAttributeValue();
                requestExam.ExamPurpose = el_encounter.ElementPath("pertinentInformation1/observationDx/value").GetAttributeValue("code");
				requestExam.ExamExplain = dto.TvpRequest.Remark;
				requestExam.FilmNum = "";
                dto.TvpRequestsExamList.Add(requestExam);

                var el_feeinfos = el_examinfo.Element("observationRequest")?.Elements("component2").ToList();
                foreach (var el_feeinfo in el_feeinfos)
                {
                    TvpRequestFee requestFee = new();
                    requestFee.SheetID = dto.TvpRequest.SheetID;
                    requestFee.ExamID = requestExam.ItemCode;
                    requestFee.FEEID = el_feeinfo.ElementPath("placerGroup/code").GetAttributeValue("code");
                    requestFee.FeeName = el_feeinfo.ElementPath("placerGroup/code/displayName").GetAttributeValue();
                    requestFee.FeeSum = el_examinfo.ElementPath("observationRequest/pertinentInformation/observation/value").GetAttributeValue();
                    requestFee.FeePrice = el_examinfo.ElementPath("observationRequest/pertinentInformation/observation/value").GetAttributeValue();
                    dto.TvpRequestsFeeList.Add(requestFee);
                }
            }

            #endregion
            return dto;
        }

        public static UpdateStateDto CreateDelRequestDto(XElement element)
        {
            UpdateStateDto dto = new() { StateType = "1", StateResult = "1" };
            var el_request = element.ElementPath("controlActProcess/subject/observationRequest");

            dto.SheetID = el_request.ElementPath("id/item").GetAttributeValue("extension");
            var el_author = el_request.Element("author");
            dto.OperatorID = el_author.ElementPath("assignedEntity/id/item").GetAttributeValue("extension");
            dto.OperatorName = el_author.ElementPath("assignedEntity/assignedPerson/name/item/part").GetAttributeValue();
            return dto;
        }

        public static List<UpdateStateDto> CreateUpdateExamStateDto(XElement element)
        {
			var result = new List<UpdateStateDto>();
            var el_requestList = element.ElementPath("controlActProcess/subject/placerGroup/component2").Elements("component2");
			foreach (var el_request in el_requestList)
			{
                UpdateStateDto dto = new() { StateType = "5"};
                dto.SheetID = el_request.ElementPath("observationRequest/id/item").GetAttributeValue("extension");
                dto.OperatorID = el_request.ElementPath("observationRequest/performer/assignedEntity/id/item").GetAttributeValue("extension");
                dto.OperatorName = el_request.ElementPath("observationRequest/performer/assignedEntity/assignedPerson/name/item/part").GetAttributeValue();
                dto.StateResult = el_request.ElementPath("observationRequest/component1/processStep/code").GetAttributeValue("code");
				result.Add(dto);
            }
            return result;
        }

        public static UpdateStateDto CreateAddFeeRequestDto(XElement element)
        {
            UpdateStateDto dto = new() { StateType = "2", StateResult = "1" };
            var el_request = element.ElementPath("controlActProcess/subject/observationRequest");
            dto.SheetID = el_request.ElementPath("id/item").GetAttributeValue("extension");

            var el_author = el_request.Element("author");
            dto.OperatorID = el_author.ElementPath("assignedEntity/id/item").GetAttributeValue("extension");
            dto.OperatorName = el_author.ElementPath("assignedEntity/assignedPerson/name/item/part").GetAttributeValue();
            return dto;
        }
        public static UpdateStateDto CreateDelFeeRequestDto(XElement element)
        {
            UpdateStateDto dto = new(){ StateType = "2", StateResult = "0" };

            var el_request = element.ElementPath("controlActProcess/subject/observationRequest");
            dto.SheetID = el_request.ElementPath("id/item").GetAttributeValue("extension");

            var el_author = el_request.Element("author");
            dto.OperatorID = el_author.ElementPath("assignedEntity/id/item").GetAttributeValue("extension");
            dto.OperatorName = el_author.ElementPath("assignedEntity/assignedPerson/name/item/part").GetAttributeValue();
            return dto;
        }

        /// <summary>
        /// 新增预约信息
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        public static string CreateIBPAddResXml(IBPExamRequestDto dto)
        {
            var xml = @$"<PRSC_IN010101UV01 ITSVersion='XML_1.0' xmlns='urn:hl7-org:v3' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='urn:hl7-org:v3 ../multicacheschemas/PRSC_IN010101UV01.xsd'>
	<!-- 消息流水号 -->
	<id root='2.16.156.10011.0' extension='{Guid.NewGuid()}'/>
	<!-- 消息创建时间 -->
	<creationTime value='{DateTime.Now:yyyyMMddHHmmss}'/>
	<!-- 服务标识,extension为唯一事件编码，区分服务事件 -->
	<interactionId root='2.16.840.1.113883.1.6' extension='JH0504'/>
	<!--处理代码，标识此消息是否是产品、训练、调试系统的一部分。D：调试；P：产品；T：训练 -->
	<processingCode code='P'/>
	<!-- 消息处理模式: A(Archive); I(Initial load); R(Restore from archive); T(Current processing) -->
	<processingModeCode/>
	<!-- 消息应答: AL(Always); ER(Error/reject only); NE(Never) -->
	<acceptAckCode code='AL'/>
	<!-- 接受者 -->
	<receiver typeCode='RCV'>
		<device classCode='DEV' determinerCode='INSTANCE'>
			<!-- 接受者ID -->
			<id>
				<item root='2.16.156.10011.0.1.1' extension='HIS'/>
			</id>
		</device>
	</receiver>
	<!-- 发送者 -->
	<sender typeCode='SND'>
		<device classCode='DEV' determinerCode='INSTANCE'>
			<!-- 发送者ID -->
			<id>
				<item root='2.16.156.10011.0.1.2' extension='PACS'/>
			</id>
		</device>
	</sender>
	<!-- 封装的消息内容 -->
	<controlActProcess classCode='CACT' moodCode='EVN'>
		<code code='PRSC_TE010100UV01' codeSystem='2.16.840.1.113883.1.6'/>
		<subject typeCode='SUBJ'>
			<actAppointment classCode='ACT' moodCode='APT ' xsi:nil='false'>
				<!--预约号 预约单流水号，全局唯一号-->
				<id extension='{dto.AppointmentNo}'/>
				<!--就诊类别:住院/门诊/急诊 -->
				<code code='{dto.VisitTypeCode}' codeSystem='2.16.156.10011.2.3.1.271'>
					<displayName value='{dto.VisitTypeName}'/>
				</code>
				<text>
					<!-- 此节点可以重复使用，作为扩展节点 -->
					<translation flavorId='节点含义描述'>取值</translation>
				</text>
				<effectiveTime xsi:type='IVL_TS'>
					<!-- 预约检查时间 -->
					<any value='{dto.AppointInspectDate}'/>
				</effectiveTime>
				<!--患者信息 -->
				<subject typeCode='SBJ'>
					<patient classCode='PAT'>
						<!--患者ID -->
						<id>
							<!-- 域ID@extension -->
							<item root='1.2.156.112635.1.2.1.2' extension='{dto.EmpiId}'/>
							<!-- 患者ID@extension -->
							<item root='2.16.156.10011.0.2.2' extension='{dto.PatientID}'/>
							<!--门（急）诊号标识@extension -->
							<item root='2.16.156.10011.1.10' extension='{dto.CardNo}'/>
							<!--住院号标识@extension-->
							<item root='2.16.156.10011.1.12' extension='{dto.PateintNo}'/>
							<!-- 就诊流水号@extension -->
							<item root='1.2.156.112635.1.2.1.6' extension='{dto.VisitSqNo}'/>
							<!-- 就诊次数@extension -->
							<item root='1.2.156.112635.1.2.1.7' extension='{dto.VisitTimes}'/>
							<!-- 预约排序号@extension-->
							<item root='1.2.156.112635.1.2.1.25' extension='{dto.AppointmentSortNum}'/>
						</id>
						<patientPerson>
							<name xsi:type='LIST_EN'>
								<item>
									<!-- 患者姓名 -->
									<part value='{dto.PatientName}'/>
								</item>
							</name>
						</patientPerson>
						<!-- 患者所在科室信息 -->
						<providerOrganization classCode='ORG' determinerCode='INSTANCE'>
							<!--病人科室编码@extension-->
							<id>
								<item extension='{dto.DeptCode}' root='2.16.156.10011.1.26'/>
							</id>
							<!--病人科室名称 -->
							<name xsi:type='BAG_EN'>
								<item>
									<part value='{dto.DeptName}'/>
								</item>
							</name>
							<contactParty classCode='CON'/>
						</providerOrganization>
					</patient>
				</subject>
				<!--预约设备 -->
				<reusableDevice typeCode='RDV' xsi:nil='false'>
					<manufacturedDevice classCode='MANU '>
						<manufacturedDevice classCode='DEV ' determinerCode='INSTANCE '>
							<!-- 预约设备编码@extension -->
							<id extension='{dto.EquipmentCode}'/>
							<!-- 预约设备名称 -->
							<name xsi:type='BAG_EN'>
								<item>
									<part value='{dto.EquipmentName}'/>
								</item>
							</name>
						</manufacturedDevice>
					</manufacturedDevice>
				</reusableDevice>
				<performer typeCode='PRF ' xsi:nil='false '>
					<assignedPerson classCode='ASSIGNED'>
						<!--预约员编码@extension -->
						<id>
							<item extension='{dto.OperCode}' root='2.16.156.10011.1.4'/>
						</id>
						<!--预约员姓名-->
						<assignedPerson determinerCode='INSTANCE' classCode='PSN'>
							<name xsi:type='BAG_EN'>
								<item>
									<part value='{dto.OperName}'/>
								</item>
							</name>
						</assignedPerson>
					</assignedPerson>
				</performer>
				<!--执行科室 -->
				<location typeCode='LOC' xsi:nil='false'>
					<serviceDeliveryLocation classCode='SDLOC '>
						<!--执行科室编码@extension -->
						<id>
							<item extension='{dto.ExecDeptCode}' root='2.16.156.10011.1.26'/>
						</id>
						<!--执行科室名称 -->
						<addr xsi:type='BAG_AD'>
							<item>
								<part value='{dto.ExecDeptName}'/>
							</item>
						</addr>
					</serviceDeliveryLocation>
				</location>
				<!--检查申请单编号 -->
				<referencedOrder typeCode='OREF' xsi:nil='false'>
					<actOrder classCode='ACT' moodCode='RQO'>
						<!--此处指的是需要进行预约的检查的检查申请单号@extension -->
						<id root='2.16.156.10011.1.24' extension='{dto.RequestNo}'/>
					</actOrder>
				</referencedOrder>
				<!-- 医嘱号 -->
				<referencedOrder typeCode='OREF'>
					<actOrder classCode='ACT' moodCode='RQO'>
						<!--此处指的是需要进行预约的检查的检查医嘱号@extension -->
						<id root='2.16.156.10011.1.28' extension='{dto.OrderId}'/>
					</actOrder>
				</referencedOrder>
			</actAppointment>
		</subject>
	</controlActProcess>
</PRSC_IN010101UV01>";
            return CreatePostXml(xml);
        }

        public static string CreateIBPUpdateResXml(IBPExamRequestDto dto)
        {
            var xml = @$"<PRSC_IN010201UV01 ITSVersion='XML_1.0' xmlns='urn:hl7-org:v3' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='urn:hl7-org:v3 ../multicacheschemas/PRSC_IN010201UV01.xsd'>
	<!-- 消息流水号 -->
	<id root='2.16.156.10011.0' extension='{Guid.NewGuid()}'/>
	<!-- 消息创建时间 -->
	<creationTime value='{DateTime.Now:yyyyMMddHHmmss}'/>
	<!-- 服务标识,extension为唯一事件编码，区分服务事件 -->
	<interactionId root='2.16.840.1.113883.1.6' extension='JH0505'/>
	<!--处理代码，标识此消息是否是产品、训练、调试系统的一部分。D：调试；P：产品；T：训练 -->
	<processingCode code='P'/>
	<!-- 消息处理模式: A(Archive); I(Initial load); R(Restore from archive); T(Current processing) -->
	<processingModeCode/>
	<!-- 消息应答: AL(Always); ER(Error/reject only); NE(Never) -->
	<acceptAckCode code='AL'/>
	<!-- 接受者 -->
	<receiver typeCode='RCV'>
		<device classCode='DEV' determinerCode='INSTANCE'>
			<!-- 接受者ID -->
			<id>
				<item root='2.16.156.10011.0.1.1' extension='HIS'/>
			</id>
		</device>
	</receiver>
	<!-- 发送者 -->
	<sender typeCode='SND'>
		<device classCode='DEV' determinerCode='INSTANCE'>
			<!-- 发送者ID -->
			<id>
				<item root='2.16.156.10011.0.1.2' extension='PACS'/>
			</id>
		</device>
	</sender>
	<!-- 封装的消息内容 -->
	<controlActProcess classCode='CACT' moodCode='EVN'>
		<code code='PRSC_TE010200UV01' codeSystem='2.16.840.1.113883.1.6'/>
		<subject typeCode='SUBJ'>
			<actAppointment classCode='ACT' moodCode='APT' xsi:nil='false'>
				<!--预约号 预约单流水号，全局唯一号-->
				<id extension='{dto.AppointmentNo}'/>
				<!--就诊类别:住院/门诊/急诊 -->
				<code code='{dto.VisitTypeCode}' codeSystem='2.16.156.10011.2.3.1.271'>
					<displayName value='{dto.VisitTypeName}'/>
				</code>
				<text>
					<!-- 此节点可以重复使用，作为扩展节点 -->
					<translation flavorId='节点含义描述'>取值</translation>
				</text>
				<effectiveTime xsi:type='IVL_TS'>
					<!-- 预约检查时间 -->
					<any value='{dto.AppointInspectDate}'/>
				</effectiveTime>
				<!--患者信息 -->
				<subject typeCode='SBJ'>
					<patient classCode='PAT'>
						<!--患者ID -->
						<id>
							<!-- 域ID@extension -->
							<item root='1.2.156.112635.1.2.1.2' extension='{dto.EmpiId}'/>
							<!-- 患者ID@extension -->
							<item root='2.16.156.10011.0.2.2' extension='{dto.PatientID}'/>
							<!--门（急）诊号标识@extension -->
							<item root='2.16.156.10011.1.10' extension='{dto.CardNo}'/>
							<!--住院号标识@extension-->
							<item root='2.16.156.10011.1.12' extension='{dto.PateintNo}'/>
							<!-- 就诊流水号@extension -->
							<item root='1.2.156.112635.1.2.1.6' extension='{dto.VisitSqNo}'/>
							<!-- 就诊次数@extension -->
							<item root='1.2.156.112635.1.2.1.7' extension='{dto.VisitTimes}'/>
							<!-- 预约排序号@extension-->
							<item root='1.2.156.112635.1.2.1.25' extension='{dto.AppointmentSortNum}'/>
						</id>
						<patientPerson>
							<name xsi:type='LIST_EN'>
								<item>
									<!-- 患者姓名 -->
									<part value='{dto.PatientName}'/>
								</item>
							</name>
						</patientPerson>
						<!-- 患者所在科室信息 -->
						<providerOrganization classCode='ORG' determinerCode='INSTANCE'>
							<!--病人科室编码@extension-->
							<id>
								<item extension='{dto.DeptCode}' root='2.16.156.10011.1.26'/>
							</id>
							<!--病人科室名称 -->
							<name xsi:type='BAG_EN'>
								<item>
									<part value='{dto.DeptName}'/>
								</item>
							</name>
							<contactParty classCode='CON'/>
						</providerOrganization>
					</patient>
				</subject>
				<!--预约设备 -->
				<reusableDevice typeCode='RDV' xsi:nil='false'>
					<manufacturedDevice classCode='MANU '>
						<manufacturedDevice classCode='DEV ' determinerCode='INSTANCE '>
							<!-- 预约设备编码@extension -->
							<id extension='{dto.EquipmentCode}'/>
							<!-- 预约设备名称 -->
							<name xsi:type='BAG_EN'>
								<item>
									<part value='{dto.EquipmentName}'/>
								</item>
							</name>
						</manufacturedDevice>
					</manufacturedDevice>
				</reusableDevice>
				<performer typeCode='PRF ' xsi:nil='false '>
					<assignedPerson classCode='ASSIGNED'>
						<!--预约员编码@extension -->
						<id>
							<item extension='{dto.OperCode}' root='2.16.156.10011.1.4'/>
						</id>
						<!--预约员姓名-->
						<assignedPerson determinerCode='INSTANCE' classCode='PSN'>
							<name xsi:type='BAG_EN'>
								<item>
									<part value='{dto.OperName}'/>
								</item>
							</name>
						</assignedPerson>
					</assignedPerson>
				</performer>
				<!--执行科室 -->
				<location typeCode='LOC ' xsi:nil='false'>
					<serviceDeliveryLocation classCode='SDLOC '>
						<!--执行科室编码@extension -->
						<id>
							<item extension='{dto.ExecDeptCode}' root='2.16.156.10011.1.26'/>
						</id>
						<!--执行科室名称 -->
						<addr xsi:type='BAG_AD'>
							<item>
								<part value='{dto.ExecDeptName}'/>
							</item>
						</addr>
					</serviceDeliveryLocation>
				</location>
				<!--检查申请单编号 -->
				<referencedOrder typeCode='OREF' xsi:nil='false'>
					<actOrder classCode='ACT' moodCode='RQO'>
						<!--此处指的是需要进行预约的检查的检查申请单号@extension -->
						<id root='2.16.156.10011.1.24' extension='{dto.RequestNo}'/>
					</actOrder>
				</referencedOrder>
				<!-- 医嘱号 -->
				<referencedOrder typeCode='OREF'>
					<actOrder classCode='ACT' moodCode='RQO'>
						<!--此处指的是需要进行预约的检查的检查医嘱号@extension -->
						<id root='2.16.156.10011.1.28' extension='{dto.OrderId}'/>
					</actOrder>
				</referencedOrder>
			</actAppointment>
		</subject>
	</controlActProcess>
</PRSC_IN010201UV01>";
            return CreatePostXml(xml);
        }

        public static string CreateIBPCancelResXml(IBPExamRequestDto dto)
		{
            var xml = @$"<PRSC_IN010201UV01 ITSVersion='XML_1.0' xmlns='urn:hl7-org:v3' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='urn:hl7-org:v3 ../multicacheschemas/PRSC_IN010201UV01.xsd'>
	<!-- 消息流水号 -->
	<id root='2.16.156.10011.0' extension='{Guid.NewGuid()}'/>
	<!-- 消息创建时间 -->
	<creationTime value='{DateTime.Now:yyyyMMddHHmmss}'/>
	<!-- 服务标识,extension为唯一事件编码，区分服务事件 -->
	<interactionId root='2.16.840.1.113883.1.6' extension='JH0506'/>
	<!--处理代码，标识此消息是否是产品、训练、调试系统的一部分。D：调试；P：产品；T：训练 -->
	<processingCode code='P'/>
	<!-- 消息处理模式: A(Archive); I(Initial load); R(Restore from archive); T(Current processing) -->
	<processingModeCode/>
	<!-- 消息应答: AL(Always); ER(Error/reject only); NE(Never) -->
	<acceptAckCode code='AL'/>
	<!-- 接受者 -->
	<receiver typeCode='RCV'>
		<device classCode='DEV' determinerCode='INSTANCE'>
			<!-- 接受者ID -->
			<id>
				<item root='2.16.156.10011.0.1.1' extension='HIS'/>
			</id>
		</device>
	</receiver>
	<!-- 发送者 -->
	<sender typeCode='SND'>
		<device classCode='DEV' determinerCode='INSTANCE'>
			<!-- 发送者ID -->
			<id>
				<item root='2.16.156.10011.0.1.2' extension='PACS'/>
			</id>
		</device>
	</sender>
	<!-- 封装的消息内容 -->
	<controlActProcess classCode='CACT' moodCode='EVN'>
		<subject typeCode='SUBJ'>
			<actAppointment classCode='ACT' moodCode='APT ' xsi:nil='false'>
				<!--预约号 预约单流水号，全局唯一号-->
				<id extension='{dto.AppointmentNo}'/>
				<!--就诊类别:住院/门诊/急诊 -->
				<code code='{dto.VisitTypeCode}' codeSystem='2.16.156.10011.2.3.1.271'>
					<displayName value='{dto.VisitTypeName}'/>
				</code>
			    <text>
					<!-- 此节点可以重复使用，作为扩展节点 -->
					<translation flavorId='节点含义描述'>取值</translation>
				</text>
				<effectiveTime xsi:type='IVL_TS'>
					<!-- 预约检查时间  -->
					<any value='{dto.AppointInspectDate}'/>
					<!-- 预约检查时间,CT时间段 ，核磁时间节点 -->
					<translation flavorId='预约检查时间'>{dto.AppointInspectTime}</translation>
				</effectiveTime>
				<!--患者信息  -->
				<subject typeCode='SBJ'>
					<patient classCode='PAT'>
						<!--患者ID -->
						<id>
							<!-- 域ID -->
							<item root='2.16.156.10011.2.5.1.5' extension='{dto.EmpiId}'/>
							<!-- 患者ID -->
							<item root='2.16.156.10011.2.5.1.4' extension='{dto.PatientID}'/>
							<!--门（急）诊号标识 -->
							<item root='2.16.156.10011.1.10' extension='{dto.CardNo}'/>
							<!--住院号标识-->
							<item root='2.16.156.10011.1.12' extension='{dto.PateintNo}'/>
							<!-- 就诊次数 -->
							<item root='2.16.156.10011.2.5.1.8' extension='{dto.VisitTimes}'/>
							<!-- 就诊流水号 -->
							<item root='2.16.156.10011.2.5.1.9' extension='{dto.VisitSqNo}'/>
							<!-- 预约排序号-->
							<item root='2.16.156.10011.2.5.1.11' extension='{dto.AppointmentSortNum}'/>
						</id>
						<patientPerson>
							<name xsi:type='LIST_EN'>
								<item>
									<!-- 患者姓名 -->
									<part value='{dto.PatientName}'/>
								</item>
							</name>
						</patientPerson>
						<providerOrganization classCode='ORG' determinerCode='INSTANCE'>
							<!--病人科室编码-->
							<id>
								<item extension='{dto.DeptCode}' root='2.16.156.10011.1.26'/>
							</id>
							<!--病人科室名称 -->
							<name xsi:type='BAG_EN'>
								<item>
									<part value='{dto.DeptName}'/>
								</item>
							</name>
							<contactParty classCode='CON'/>
						</providerOrganization>
					</patient>
				</subject>
				<!--预约设备  -->
				<reusableDevice typeCode='RDV' xsi:nil='false'>
					<manufacturedDevice classCode='MANU '>
						<manufacturedDevice classCode='DEV ' determinerCode='INSTANCE '>
							<!-- 预约设备编码 -->
							<id extension='{dto.EquipmentCode}'/>
							<!-- 预约设备名称 -->
							<name xsi:type='BAG_EN'>
								<item>
									<part value='{dto.EquipmentName}'/>
								</item>
							</name>
						</manufacturedDevice>
					</manufacturedDevice>
				</reusableDevice>
				<performer typeCode='PRF ' xsi:nil='false '>
					<assignedPerson classCode='ASSIGNED'>
						<!--预约员编码 -->
						<id>
							<item extension='{dto.OperCode}' root='2.16.156.10011.1.4'/>
						</id>
						<!--预约员姓名-->
						<assignedPerson determinerCode='INSTANCE' classCode='PSN'>
							<name xsi:type='BAG_EN'>
								<item>
									<part value='{dto.OperName}'/>
								</item>
							</name>
						</assignedPerson>
					</assignedPerson>
				</performer>
				<!--执行科室  -->
				<location typeCode='LOC ' xsi:nil='false'>
					<serviceDeliveryLocation classCode='SDLOC '>
						<!--执行科室编码 -->
						<id>
							<item extension='{dto.ExecDeptCode}' root='2.16.156.10011.1.26'/>
						</id>
						<!--执行科室名称 -->
						<addr xsi:type='BAG_AD'>
							<item>
								<part value='{dto.ExecDeptName}'/>
							</item>
						</addr>
					</serviceDeliveryLocation>
				</location>
				<!--检查申请单编号 -->
				<referencedOrder typeCode='OREF' xsi:nil='false'>
					<actOrder classCode='ACT' moodCode='RQO'>
						<!--此处指的是需要进行预约的检查的检查申请单号 -->
						<id root='2.16.156.10011.1.24' extension='{dto.RequestNo}'/>
					</actOrder>
				</referencedOrder>
				<!--  医嘱号  -->
				<referencedOrder typeCode='OREF'>
					<actOrder classCode='ACT' moodCode='RQO'>
						<!--此处指的是需要进行预约的检查的检查医嘱号 -->
						<id root='2.16.156.10011.1.28' extension='{dto.OrderId}'/>
					</actOrder>
				</referencedOrder>
			</actAppointment>
		</subject>
	</controlActProcess>
</PRSC_IN010201UV01>";
            return CreatePostXml(xml);

        }

        private static string CreatePostXml(string message)
        {
            var xml = $@"<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:good='http://goodwillcis.com'>
   <soapenv:Header>
      <good:JiaheSecurity>
         <!--Optional:-->
         <good:UserName>?</good:UserName>
         <!--Optional:-->
         <good:Password>?</good:Password>
         <!--Optional:-->
         <good:Timestamp>?</good:Timestamp>
         <!--Optional:-->
         <good:FromSYS>?</good:FromSYS>
         <!--Optional:-->
         <good:IV>?</good:IV>
      </good:JiaheSecurity>
   </soapenv:Header>
   <soapenv:Body>
      <good:HIPMessageServer>
         <!--Optional:-->
         <good:Message><![CDATA[{message}]]></good:Message>
      </good:HIPMessageServer>
   </soapenv:Body>
</soapenv:Envelope>";
            xml = xml.Replace("\'", "\"");
            return xml;
        }
    }
}
